import { Component, OnInit, ViewChild } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { JsonApiService } from 'app/core/api/json-api.service'
import { config } from '../../shared/smartadmin.config'
import { DatePickerModule } from '../../shared/date-picker/date-picker.module'

declare var $: any
@Component({
  selector: 'sa-outsource-processing-order',
  templateUrl: './outsource-processing-order.component.html',
  styleUrls: ['./outsource-processing-order.component.css']
})
export class OutsourceProcessingOrderComponent implements OnInit {
  tableData: any = [] // table的表单数据
  totalCounts: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  fileUp: string = ''
  fileToUpload: File = null //上传文件回调参数
  searchKey: any = '' // 用户的搜索关键字
  // 标志是否选择车辆的
  isShowDelete: any = false //是否有删除权限
  startTime_search: string = ''
  endTime_search: string = ''
  specifyId = {
    picker1: 'datetimepicker3',
    picker2: 'datetimepicker4'
  }
  specifyTime = {
    startTime: '',
    endTime: ''
  }

  tableSearch: any = {
    consignorNumber: '', //委外编号
    supplierName: '', //供应商
    materialNumber: '', //物料编码
    materialName: '' //物料名称
  }

  uploadPermission: boolean = false
  delPermission: boolean = false

  constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
    activatedRoute.queryParams.subscribe(queryParams => {})
  }
  ngOnInit() {
    this.initBtn()
    this.load()
  }
  //初始化权限按钮
  initBtn() {
    const btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_supplyChain:opOrder')))
    if (!btnData) {
      return
    }
    for (let item of btnData) {
      if (item.sourceKey === 'opOrder:uploadBtn' && item.parentId) {
        this.uploadPermission = true
      }
      if (item.sourceKey === 'opOrder:delBtn' && item.parentId) {
        this.delPermission = true
      }
    }
  }

  load() {
    let param = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        // searchKey: common.stringTrim(this.searchKey),
        startTime: this.startTime_search,
        endTime: this.endTime_search,
        ...this.tableSearch
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(param)
    this.jsonApiService.http('dtsConsignorExtraWorkOrder/page.html', reqdata).subscribe(result => {
      if (result.isSuccess && result.exhibitDatas) {
        this.tableData = result.exhibitDatas
        this.totalCounts = result.recordCount
      }
    })
  }
  // 分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  // 刷新表
  refresh() {
    this.load()
  }
  // 删除续费记录
  delPurchase(row) {
    this.jsonApiService.confirm_message('此操作将删除该条数据,确认要删除？').then(() => {
      this.jsonApiService.http_get('dtsConsignorExtraWorkOrder/deleteById.html?id=' + row.id).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }
  // 表单查询
  table_search() {
    this.curPage = 1
    this.load()
  }

  // 删除输入
  delKey(type) {
    this.tableSearch[type] = ''
  }

  isUpload: any = '' //是否是导入
  isScroTopNum: any = 0 //当用户重新点开添加再进行点击车辆选择时才滚动到头部 其他时候不滚动
  // 重置添加表
  resetForm() {
    this.renewal = {
      renewalData: [],
      payDate: common.getNowTime(), //缴费时间
      renewalTime: '', // 续费时长
      remark: '' //备注
    }
  }
  // 关闭添加弹框
  closeRenewalModal(modal) {
    $('#addRenewal').data('bootstrapValidator').resetForm()
    modal.hide()
  }
  //时间change回调
  datePickerSelected(val) {
    this.renewal.payDate = val.endTime
  }
  // 添加时传递给后端的对象
  renewal: any = {
    renewalData: [],
    payDate: '',
    renewalTime: '',
    remark: '' //备注
  }

  // 显示导入弹框
  showImportModal(modal) {
    // 清空选择的文件
    modal.show()
    this.fileToUpload = null
  }
  // 关闭导入弹窗
  cancelUp(modal) {
    modal.hide()
    this.fileToUpload = null
  }

  clearFile() {
    this.fileUp = ''
  }
  //文件上传change回调
  fileChange(files: FileList) {
    this.fileToUpload = files.item(0)
    const isEXCEL =
      this.fileToUpload.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      this.fileToUpload.type === 'application/vnd.ms-excel'
    if (!isEXCEL) {
      this.jsonApiService.message('上传文件只能是 excel格式!')
      this.fileToUpload = null
      return
    }
  }
  //导入submit
  submitData(modal1, modal2) {
    let postParam = new FormData()
    postParam.append('file', this.fileToUpload)
    if (!this.fileToUpload) {
      this.jsonApiService.message('请上传文件')
      return false
    }
    this.jsonApiService.form_http('dtsConsignorExtraWorkOrder/importExcelData.html', postParam).subscribe(data => {
      if (data.success) {
        modal1.hide()
        this.fileToUpload = null
        this.showSubmitCheck(modal2, data.data)
      }
    })
  }
  // 接收子组件传递过来的数据
  getSelectTableTime(time) {
    this.startTime_search = time.startTime
    this.endTime_search = time.endTime
  }

  //初始化日期
  initRenewalDate() {
    var that = this
    System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
      System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
        $('#payDate')
          .datetimepicker({
            //时间插件
            format: 'yyyy-mm-dd hh:ii:ss',
            language: 'zh-CN',
            autoclose: true,
            endDate: common.getNowTime()
          })
          .on('changeDate', function (e) {
            var date = e.date
            if (!date) {
              return
            }
            var time = common.getTimeMmss(date)
            // $("#payDate").datetimepicker("setEndDate", time);
            that.renewal.payDate = time
          })
      })
    })
  }

  /**
   * 提交核对
   */
  checkCurPage: number = 1
  checkPageSize: number = 10
  checkTotalCounts: number = 0 //分页总条数
  submitCheckTableData: any = [] //核对列表
  result: string = '' //提交前状态
  version: string = ''
  allSize: any = '' //总数量
  success: any = '' //成功
  errSize: any = '' //失败
  //显示
  showSubmitCheck(modal, data) {
    this.checkCurPage = 1
		this.checkPageSize = 10
    this.version = data.version
    this.allSize = data.allSize //总数量
    this.success = data.success //成功
    this.errSize = data.errSize //失败
    this.check_table_search(modal)
  }
  //关闭
  cancelSubmitCheck(modal2, modal1) {
    this.result = ''
    this.submitCheckTableData = []
    this.version = ''
    modal2.hide()
    modal1.show()
  }
  queryCheckTable() {
    this.checkPageSize = 10
    this.checkCurPage = 1
    this.check_table_search('')
  }
  //查询
  check_table_search(modal) {
    let param = {
      pageSize: this.checkPageSize,
      nowPage: this.checkCurPage,
      parameters: {
        version: this.version,
        result: this.result
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(param)
    this.jsonApiService.http('dtsConsignorExtraWorkOrder/getTempList.html', reqdata).subscribe(result => {
      if (result.isSuccess) {
        this.submitCheckTableData = result.exhibitDatas
        if (modal) modal.show()
        for (let item of this.submitCheckTableData) {
          item['isChecked'] = false
        }
        this.allChecked = false
        this.selected = []
        this.checkTotalCounts = result.recordCount
        this.numMessage = result.message
        this.rowId = ''
      } else {
        this.numMessage = ''
      }
    })
  }
  //提交
  submitCheck(modal) {
    let isSubmit = true
    if (this.submitCheckTableData.length == 0) {
      this.jsonApiService.message('暂无需要提交核对的数据')
      return
    }

    // for (let i = 0; i < this.submitCheckTableData.length; i++) {
    //   if (this.submitCheckTableData[i].result == 2) {
    //     isSubmit = false
    //     this.jsonApiService.message('列表中存在失败状态的数据')
    //     return
    //   }
    // }

    // if (isSubmit) {
      this.jsonApiService
        .http_obj('dtsConsignorExtraWorkOrder/insertDtsBuyOrder.html', { version: this.version })
        .subscribe(result => {
          this.jsonApiService.message(result.message)
          if (result.success) {
            this.result = ''
            this.submitCheckTableData = []
            this.version = ''
            this.resetForm()
            modal.hide()
            this.load()
          }
        })
    // }
  }
  //删除
  delSubmitCheck(row) {
    this.jsonApiService.confirm_message('此操作将删除临时数据,确认要删除').then(() => {
      let reqdata = 'ids=' + row.id
      this.jsonApiService.http('dtsConsignorExtraWorkOrder/deleteTempByIds.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.check_table_search('')
        }
      })
    })
  }

  // 分页回调
  checkPaginate(e) {
    this.checkCurPage = e.page + 1
    this.checkPageSize = e.rows
    this.check_table_search('')
  }

  // 刷新表
  checkRefresh() {
    this.check_table_search('')
  }

  editcheckForm: any = {
    supplierName: '',
    date: '',
    consignorNumber: '',
    materialNumber: '',
    materialName: '',
    specification: '',
    units: '',
    count: '',
    deliveryDate: '',
    id: '',
    applyDepartmet: '',
    applicant: '',
    errMsg: ''
  }
  //编辑
  editSubmitCheck(row, modal) {
    // let reqdata = 'id=' + row.id;
    //获取编辑详情
    for (let item in row) {
      this.editcheckForm[item] = row[item]
    }
    modal.show()
  }

  //关闭编辑
  closeEditSubmitCheck(modal) {
    modal.hide()
  }

  numMessage: any = '' //显示数量
  //批量删除
  allChecked: boolean = false //table全选状态值
  selected: any[] = [] //row选择的数据
  rowId: string = '' //批量
  //table 全部选中
  allSelected() {
    this.allChecked = !this.allChecked
    if (!this.allChecked) {
      for (let item of this.submitCheckTableData) {
        item['isChecked'] = false
      }
      this.selected = []
      this.rowId = ''
    } else {
      var temArr = []
      for (let item of this.submitCheckTableData) {
        item['isChecked'] = true
        temArr.push(item.id)
        this.selected.push(item)
      }
      for (let item of this.selected) {
        temArr.push(item.rowId)
      }
      this.rowId = temArr.join(',')
    }
  }
  //table复选框数据row选中事件回调:处理选中状态和deviceId
  rowSelected(row, e, index) {
    var index = $.inArray(row, this.selected)
    if (index === -1) {
      row.isChecked = true
      this.selected.push(row)
    } else {
      row.isChecked = false
      this.selected.splice(index, 1)
    }
    var temArr = []
    for (let item of this.selected) {
      temArr.push(item.id)
    }
    this.rowId = temArr.join(',') //处理deviceId,与后台接口交互参数
    this.selected.length === this.submitCheckTableData.length ? (this.allChecked = true) : (this.allChecked = false) //判断是否全选状态
  }
  batchDelete() {
    console.log(this.selected, this.rowId)
    if (this.selected.length && this.rowId != '') {
      this.jsonApiService.confirm_message('此操作将删除临时数据,确认要删除？').then(() => {
        let reqdata = 'ids=' + this.rowId
        this.jsonApiService.http('dtsConsignorExtraWorkOrder/deleteTempByIds.html', reqdata).subscribe(data => {
          this.jsonApiService.message(data.message)
          this.check_table_search('')
        })
      })
    } else {
      this.jsonApiService.message('请选中最少一条数据')
    }
  }
}
